<template>
  <div id="">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/Home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div class="card-header">
        <div style="margin: 15px;" class="input-width">
          <el-input v-model="pageinfo.query" @input="select" @keyup.enter.native="select" clearable placeholder="请输入内容"
                    class="input-with-select">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <el-button type="primary" calss="btn" @click="isAddUser = true">添加用户</el-button>
      </div>
      <el-table
          border
          :data="tableData"
          style="width: 100%">
        <el-table-column
            type="index"
            label="#"
            width="180">
        </el-table-column>
        <el-table-column
            prop="username"
            label="姓名"
            width="180">
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="180">
        </el-table-column>
        <el-table-column
            prop="mobile"
            label="电话">
        </el-table-column>
        <el-table-column
            prop="role_name"
            label="角色">
        </el-table-column>
        <el-table-column
            label="时间">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | Data }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div @click="sco(scope)">
              <el-switch
                  v-model="scope.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <!--        按钮-->
        <el-table-column
            label="操作"
        >
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-edit"
                       @click="change(scope.row)"
            >
            </el-button>
            <el-button size="mini"
                       type="danger"
                       icon="el-icon-delete"
                       @click="open(scope.row)">
            </el-button>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top">
              <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-setting"
                  @click="changeRole(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    分页-->
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageinfo.pagenum"
          :page-sizes="[1,2,4,6,8]"
          :page-size="2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="isAddUser">
      <el-form :model="addUserDiaData" :rules="addUserDiaRules" ref="addUserDia">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="addUserDiaData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-input v-model="addUserDiaData.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input v-model="addUserDiaData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="120px" prop="mobile">
          <el-input v-model="addUserDiaData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddUser = false">取 消</el-button>
        <el-button type="primary" @click="addUserConfirm"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
    <!-- 修改用户-->
    <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible">
      <el-form :model="changeForm" :rules="changeForms" ref="changeFormsDia">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
          <el-input disabled v-model="changeForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="changeForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="changeForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDor">取 消</el-button>
        <el-button type="primary" @click="closeDor">确 定</el-button>
      </div>
    </el-dialog>
    <!--   分配权限弹出框-->
    <el-dialog title="收货地址" :visible.sync="jurisdictionForm">
      <el-form :model="jForm">
        <el-form-item label="当前的用户：" :label-width="formLabelWidth">
          <div>{{ this.CurrentUser }}</div>
        </el-form-item>
        <el-form-item label="当前的角色：" :label-width="formLabelWidth">
          <div>{{ this.CurrentRole }}</div>
        </el-form-item>
        <el-form-item label="分别配新角色" :label-width="formLabelWidth">
          <el-select v-model="jForm.id" placeholder="请选择">
            <el-option
                v-for="(item,index) in rolesData"
                :key="index"
                :label="item.roleName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backs">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {user, usersuId, addUserAPI, delUsers, changeUser, changeRoles, roles} from '@/utils/api'
import _ from 'lodash'

export default {
  name: '',
  props: {},
  data() {
    //邮箱验证规则
    const checkEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/g;   //用户名@xxxx.com.cn
      if (!reg.test(value)) {
        return callback(new Error('邮箱不合法，请输入重新'))
      }
      callback();
    }
    //手机号验证规则
    const checkMobile = (rule, value, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/g;
      if (!reg.test(value)) {
        return callback(new Error('手机号不合法，请输入重新手机号'))
      }

      callback()

    }
    return {
      query: {},
      pageinfo: {
        query: '',
        pagenum: 1,
        pagesize: 3,
      },
      formLabelWidth: '120px',
      tableData: [],
      rolesData: [],
      total: 0,
      //添加用户对话框要绑定的数据
      addUserDiaData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //添加用户对话表单验证规则
      addUserDiaRules: {
        username: [
          {required: true, message: '请填写用户名', trigger: 'blur'},
          {min: 6, max: 16, message: '请输入长度在6到16之间的字符个数', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请填写密码', trigger: 'blur'},
          {min: 6, max: 16, message: '请输入长度在6到16之间的字符个数', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请填写邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请填写手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      //是否显示添加用户对话框
      isAddUser: false,
      //修改用户 对话框数据
      dialogFormVisible: false,
      changeFormId: '',
      changeForm: {
        name: '',
        email: '',
        mobile: '',
      },
      //添加用户对话表单验证规则
      changeForms: {
        name: [],
        email: [
          {required: true, message: '请填写邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请填写手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      // 分配权限
      CurrentUser: '',
      CurrentRole: '',
      CurrentId: '',
      UserId: '',
      jurisdictionForm: false,
      jForm: {
        id: '',
      },
    }
  },
  // 子组件转换
  components: {},
  // 数据引入 created
  created() {
    this.users()
    this.role()
  },
  mounted() {
  },
  //点击函数事件
  methods: {
    //搜索
    select: _.throttle(function () {
      this.users()
    }, 2000),
    //确定要添加的用户
    addUserConfirm() {
      //整体表单的验证
      this.$refs.addUserDia.validate(async valid => {
        if (!valid) return;
        //调后台接口，将新用户添加到向后台
        const res = await addUserAPI(this.addUserDiaData)
        //关闭对话框
        this.isAddUser = false
        //重新拉取用户列表
        this.users()
      })
    },
    //修改用户
    change(i) {
      // console.log(i)
      this.changeFormId = i.id
      this.changeForm.name = i.username
      this.changeForm.email = i.email
      this.changeForm.mobile = i.create_time
      this.dialogFormVisible = true
      var id = this.changeFormId
      console.log(this.changeForm)
    },
    closeDor() {
      var id = this.changeFormId
      console.log(this.changeForm)
      changeUser(id, this.changeForm).then(res => {
        this.users()
      })
      this.dialogFormVisible = false
    },
    //分页码
    handleSizeChange(val) {
      this.pageinfo.pagesize = val
      this.users()
    },
    handleCurrentChange(val) {
      this.pageinfo.pagenum = val
      this.users()
    },
    // 状态
    sco(i) {
      let {id, mg_state} = i.row
      usersuId(id, mg_state).then(res => {
      })
    },
    // 用户数据接口
    async users() {
      //调用户列表接口
      const res = await user(this.pageinfo);
      // console.log("用户列表：", res);
      let {total, users} = res;
      this.tableData = users;
      this.total = total;
    },
    //角色数据接口
    async role() {
      const res = await roles();
      console.log(res)
      this.rolesData = res
    },
    //删除
    open(i) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = i.id
        delUsers(id).then(res => {
          this.users()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 修改用户状态
    changeRole(i) {
      console.log(i)
      this.CurrentUser = i.username
      this.CurrentRole = i.role_name
      this.jForm.name = i.role_name
      this.UserId = i.id
      console.log(i.id)
      this.jurisdictionForm = true
    },
    //修改权限
    backs() {
      this.jurisdictionForm = false
    },
    add() {
      console.log(this.jForm.id)
      var id = this.UserId
      var rid = this.jForm.id
      console.log(id, rid)
      this.jurisdictionForm = false
      changeRoles(id, {rid}).then(() => {
        this.users()
      })
    }
  },
//计算事件
  computed: {},
//数据监听
  watch: {},
//过滤器
  filters: {},
//设定自定义指令
  directives: {},
}
</script>
<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  margin-top: 20px;
}

.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.card-header {
  width: 600px;
  height: 80px;
}

.input-width {
  width: 400px;
  display: inline-block;
}

/deep/ {
  .item[data-v-356d4cf9] {
    padding: 7px 15px;
  }
}
</style>